#!/bin/bash -e

LOCAL_IF=${LOCAL_IF:-$HOSTNAME-eth0}
EXT_IF=eth0

function finished {
    echo gateway terminating
}
trap finished EXIT

echo Starting networking for $LOCAL_IF and $EXT_IF

while ! ifconfig -a | fgrep -q $LOCAL_IF; do
    echo Waiting for interface $LOCAL_IF to exist...
    sleep 1
done

# Enable a web-server for configuration access.
mkdir -p /tmp/public
(cd /tmp/public; python -m SimpleHTTPServer &)

# Enable NAT to the outside world, through the docker bridge.
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -o $EXT_IF -j MASQUERADE
iptables -A FORWARD -i $EXT_IF -o $LOCAL_IF -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i $LOCAL_IF -o $EXT_IF -j ACCEPT

# Pick a random DHCP range to force clients to pick a new address.
subnet=$((RANDOM % 99 + 1))
echo Configuring with subnet 10.20.$subnet.XX
echo dhcp-range=10.20.$subnet.100,10.20.$subnet.254 >> /etc/dnsmasq.conf

if ! ip addr show dev $LOCAL_IF | fgrep -q 'inet '; then
  echo Assigning gateway address 10.20.$subnet.1/16
  ip addr add 10.20.$subnet.1/16 dev $LOCAL_IF
fi

echo dhcp-host=*,ignore >> /etc/dnsmasq.conf

echo Blocking for all eternity.
./autorestart_dnsmasq
